#! /usr/bin/env python

#############################################################################
# add_torrent.py: Sample module for adding torrents to an SQLite database.
#############################################################################
# Copyright (C) 2012
#
# Authors: Dan Larkin <danielhlarkin@gmail.com>
#          Yonatan Naamad <cached@gmail.com>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#############################################################################

import bencode
import hashlib
import sys
import math
import struct
import sqlite3

__author__ = "Daniel Larkin and Yonatan Naamad"
__copyright__ = "Copyright 2011, Daniel Larkin and Yonatan Naamad"
__credits__ = ["Daniel Larkin", "Yonatan Naamad"]
__license__ = "GPL"
__version__ = "0.1.0a"
__maintainer__ = "Daniel Larkin and Yonatan Naamad"
__email__ = "danielhlarkin@gmail.com,cached@gmail.com"
__status__ = "Prototype"

CHUNK_SIZE = 32+256

def compute_hash(torrent_data):
    metainfo = bencode.bdecode(torrent_data)
    return hashlib.sha1(bencode.bencode(metainfo['info'])).digest()
    
def compute_size(torrent_data):
    metainfo = bencode.bdecode(torrent_data)
    return metainfo['info']['length']

def add_torrent(db_path, torrent_path, min_bw, max_bw):
    try:
        f = open(torrent_path,'rb')
        d = f.read()
        f.close()
    except:
        raise IOError("Torrent file '%s' not found." % torrent_path)
        
    info_hash = compute_hash(d)
    file_size = compute_size(d) / 1024 / 1024

    db_conn = sqlite3.connect(db_path, isolation_level = None)
    c = db_conn.cursor()
    
    c.execute("""INSERT INTO torrents (path, size, t_min, t_max, hash) VALUES (?,?,?,?,?)""",
              (torrent_path, file_size, min_bw, max_bw, sqlite3.Binary(info_hash)))
              
    #change the following line if you wish to allow for multiple users
    c.execute("""INSERT INTO permissions (torrent_id, user_id) VALUES (?, ?)""",
              (c.lastrowid, 1))
              
    db_conn.commit()
    
    c.close()
    db_conn.close()
    
if __name__ == '__main__':
    if len(sys.argv) != 5:
        print "Usage: ./%s <db_path> <torrent_path> <min_bw> <max_bw>" % sys.argv[0]
    else:
        add_torrent(sys.argv[1],sys.argv[2],int(sys.argv[3]),int(sys.argv[4]))
